/*
 * @lc app=leetcode.cn id=640 lang=typescript
 *
 * [640] 求解方程
 */

// @lc code=start
function solveEquation(equation: string): string {
  // 因数
  let factor = 0;
  // 常数
  let constant = 0;
  let n = equation.length;
  let idx = 0;
  // 默认等号左边符号
  let sign = 1;
  while (idx < n) {
    // 等号右边，默认符号位负
    if (equation[idx] === '=') {
      sign = -1;
      idx++;
      continue;
    }

    // 临时符号，处理数字正负
    let signTemp = sign;
    let num = 0;
    // 处理是否是数字
    let isNumber = false;
    if (equation[idx] === '-' || equation[idx] === '+') {
      signTemp = equation[idx] === '-' ? -sign : sign;
      idx++;
    }
    // 处理数字
    while (idx < n && equation[idx] >= '0' && equation[idx] <= '9') {
      num = num * 10 + Number(equation[idx]);
      idx++;
      isNumber = true;
    }
    // 处理是否是因数
    if (idx < n && equation[idx] === 'x') {
      factor += isNumber ? signTemp * num : signTemp;
      idx++;
    } else {
      constant += signTemp * num;
    }
  }

  if (factor === 0) {
    return constant === 0 ? 'Infinite solutions' : 'No solution';
  }

  return `x=${-constant / factor}`;
}
// @lc code=end
